package org.zoomdev.zoom.web.rendering.impl;

import jakarta.servlet.http.HttpServletResponse;
import org.zoomdev.zoom.common.utils.Classes;
import org.zoomdev.zoom.web.action.ActionContext;
import org.zoomdev.zoom.web.exception.StatusException;
import org.zoomdev.zoom.web.html.HtmlBuilder;
import org.zoomdev.zoom.web.rendering.Rendering;

import java.io.IOException;

public final class HtmlRendering implements Rendering {

    public static final String EXT = "html";

    @Override
    public boolean render(ActionContext context) throws Exception {
        render(context.getRenderObject(), context.getResponse());
        return true;
    }

    public static void render(Object result, HttpServletResponse response) throws IOException {
        String str = null;
        HtmlBuilder builder = new HtmlBuilder();
        int status = 200;
        if (result instanceof Throwable) {
            if (result instanceof StatusException) {
                status = ((StatusException) result).getStatus();
                builder.status(status);
                str = ((StatusException) result).getMessage();
            }
            if (str == null) {
                str = Classes.formatStackTrace((Throwable) result);
            }
        } else {
            str = String.valueOf(result);
        }

        if (status != 200) {
            builder.h(str, 1);
        } else {
            builder.pre(str);
        }
        builder.writeTo(response);
    }
}
